package com.kye.express.business.tcl.detail;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.NetworkMonitorUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.databinding.ActivityTclDetailBinding;
import com.kye.express.utils.GlideImageLoader;
import com.kye.express.utils.IntentUtil;
import com.kye.express.utils.WebViewManager;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.tcl.ResponseTCLGoodsDetailsBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.kye.nb.banner.listener.OnBannerListener;

import java.util.ArrayList;

public class TCLDetailActivity extends BaseToolbarActivity implements TCLDetailContract.TCLDetailView {

    private static final String TAG = TCLDetailActivity.class.getSimpleName();

    private TCLDetailContract.TCLDetailPresenter mPresenter;
    private ActivityTclDetailBinding mBinding;
    private User userInfo;

    private String phone;
    private String productId;
    private ArrayList<String> urlData;
    private String marketingTelphone = "";

    MaterialDialog mDialog = null;

    public static void startActivity(Context context, String phone, String productId, ArrayList<String> urlAddress) {
        Intent intent = new Intent(context, TCLDetailActivity.class);
        intent.putExtra(Constants.KEY_PHONE, phone);
        intent.putExtra(Constants.KEY_PRODUCTID, productId);
        intent.putStringArrayListExtra(Constants.KEY_URLADDRESS, urlAddress);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        initEvents();
        initData();
    }

    @Override
    public void onStart() {
        super.onStart();
        mBinding.banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        mBinding.banner.stopAutoPlay();
    }

    @Override
    protected void onDestroy() {
        if (mPresenter != null) {
            mPresenter.unbind();
        }
        if (mBinding.webviewTclDetail != null) {
            mBinding.webviewTclDetail.loadDataWithBaseURL(null, "", "text/html; charset=utf-8", "UTF-8", null);
            mBinding.webviewTclDetail.clearHistory();
            ((ViewGroup) mBinding.webviewTclDetail.getParent()).removeView(mBinding.webviewTclDetail);
            mBinding.webviewTclDetail.destroy();
        }
        super.onDestroy();
    }

    private void initViews() {
        initDataBinding();
        initPresenter();
        initToolbar();
    }

    private void initEvents() {


        mBinding.statuslayoutTclDetail.setOnLoadingListener(() ->
                request(phone, productId)
        );

        RxView.clicks(mBinding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statuslayoutTclDetail.showLoadingView();
                });
        RxView.clicks(mBinding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statuslayoutTclDetail.showLoadingView();
                });
        RxView.clicks(mBinding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statuslayoutTclDetail.showLoadingView();
                });

        RxView.clicks(mBinding.buttonTclGo)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe(o -> {
                    if (null == userInfo.getCustomCode() || 0 >= userInfo.getCustomCode().length()) {
                        // 还未绑定客户编码
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(TCLDetailActivity.this)
                                    .title("温馨提示")
                                    .content(R.string.tcl_detail_unbounded)
                                    .positiveText(R.string.common_call)
                                    .negativeText(R.string.common_cancel)
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            IntentUtil.call(TCLDetailActivity.this, "4008098098");
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    } else {
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(TCLDetailActivity.this)
                                    .title("温馨提示")
                                    .content(R.string.tcl_detail_unbounded)
                                    .positiveText(R.string.common_confirm)
                                    .negativeText(R.string.common_cancel)
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            IntentUtil.call(TCLDetailActivity.this, marketingTelphone);
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
    }

    private void initData() {
        getIntentExtra();
        initBanner();
        mBinding.statuslayoutTclDetail.showLoadingView();
    }

    private void initDataBinding() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_tcl_detail);
    }

    private void initPresenter() {
        mPresenter = new TCLDetailContract.TCLDetailPresenter();
        mPresenter.bind(this);
    }

    private void initToolbar() {
        setUpToolbar(mBinding.toolbarTclDetail);
        setTitle(getString(R.string.tcl_detail_title));
    }

    private void initBanner() {
        mBinding.banner.setDelayTime(4000);
        mBinding.banner.setImageLoader(new GlideImageLoader());
        mBinding.banner.setImages(urlData);
        mBinding.banner.start();
    }

    private void getIntentExtra() {
        phone = getIntent().getStringExtra(Constants.KEY_PHONE);
        productId = getIntent().getStringExtra(Constants.KEY_PRODUCTID);
        urlData = getIntent().getStringArrayListExtra(Constants.KEY_URLADDRESS);
    }

    private void request(String phone, String productId) {
        NetworkMonitorUtils.networkObservable(this)
                .compose(this.bindToLifecycleDestroy())
                .map((connectivity) -> {
                    NetworkInfo.State state = connectivity.getState();
                    switch (state) {
                        case CONNECTED:
                        case CONNECTING:
                            return true;
                        case DISCONNECTED:
                        case DISCONNECTING:
                            return false;
                        default:
                            return false;
                    }
                })
                .subscribe((Boolean) -> {
                    if (Boolean) {
                        mPresenter.requestToTCLGoodsDetail(phone, productId);
                    } else {
                        mBinding.statuslayoutTclDetail.showErrorNetworkView();
                        ToastManager.show(this, getString(R.string.common_net_error));
                    }
                });
    }

    @Override
    public void onLoadDataUser(User user) {
        if (user == null || !user.isLogin()) {
            ToastManager.show(this, getString(R.string.common_login));
            LoginActivity.startActivity(this);
        } else {
            userInfo = user;
            marketingTelphone = userInfo.getMarketingTelphone();
        }
    }

    @Override
    public void onSuccessLoadData(OpenApiResult<ResponseTCLGoodsDetailsBean> bean) {
        if (bean != null) {
            if (bean.getCode() == Constants.ResponseCode_SUCCESS) {
                ResponseTCLGoodsDetailsBean data = bean.getData();
                if (data != null) {
                    mBinding.statuslayoutTclDetail.showContentView();
                    mBinding.textviewTclDetailName.setText(data.getProductName());
                    mBinding.textviewTclDetailPrice.setText(data.getPrice());
                    setWebView(data);
                } else {
                    mBinding.statuslayoutTclDetail.showErrorServerView();
                }
            } else {
                ToastManager.show(this, bean.getMsg());
                mBinding.statuslayoutTclDetail.showErrorServerView();
            }
        } else {
            Logger.d(TAG + " - onSuccessLoadData - bean is null");
            mBinding.statuslayoutTclDetail.showErrorServerView();
        }
    }

    @Override
    public void onApiError(OpenApiResult<ResponseTCLGoodsDetailsBean> result, int code, String msg) {
        mBinding.statuslayoutTclDetail.showErrorServerView();
        ToastManager.show(this, msg);
        Logger.d(TAG + " - onApiError - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void onOtherError(Throwable e) {
        mBinding.statuslayoutTclDetail.showErrorNetworkView();
        ToastManager.show(this, getString(R.string.common_net_error));
        Logger.d(TAG + " - onOtherError : " + e.getMessage());
        e.printStackTrace();
    }

    private void setWebView(ResponseTCLGoodsDetailsBean data) {
        mBinding.webviewTclDetail.loadUrl("file:///android_asset/tcl/tclShopDetatils.html");

        mBinding.webviewTclDetail.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                mBinding.webviewTclDetail.loadUrl("javascript:setTimbreKardon(" + data.getTimbre().isKardon() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setTimbreNautilus(" + data.getTimbre().isNautilus() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setTimbreIndependentdrive(" + data.getTimbre().isIndependentdrive() + ")");

                mBinding.webviewTclDetail.loadUrl("javascript:setSourceTencentTv(" + data.getResources().isTencentTv() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setSourceFriendsSong(" + data.getResources().isFriendsSong() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setSourceWeChat(" + data.getResources().isWeChat() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setSourceSports(" + data.getResources().isSports() + ")");

                mBinding.webviewTclDetail.loadUrl("javascript:setScreen('" + data.getScreen() + "')");
                mBinding.webviewTclDetail.loadUrl("javascript:setScreenSize('" + data.getScreenSize() + "')");

                mBinding.webviewTclDetail.loadUrl("javascript:setOperationSystem('" + data.getOperation().getSystem() + "')");
                mBinding.webviewTclDetail.loadUrl("javascript:setOperationRemoteControl('" + data.getOperation().getRemoteControl() + "')");

                mBinding.webviewTclDetail.loadUrl("javascript:setHardwareToProcessor('" + data.getHardware().getProcessor() + "')");
                mBinding.webviewTclDetail.loadUrl("javascript:setHardwareRamandrom('" + data.getHardware().getRamandrom() + "')");
                mBinding.webviewTclDetail.loadUrl("javascript:setHardwareWifi('" + data.getHardware().getWifi() + "')");
                mBinding.webviewTclDetail.loadUrl("javascript:setHardwareHdmiAndUsb(" + data.getHardware().isHdmiAndUsb() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setHardwareDts(" + data.getHardware().isDts() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setHardwareMicrophone(" + data.getHardware().isMicrophone() + ")");

                mBinding.webviewTclDetail.loadUrl("javascript:setPictureMaterialDisplaymaterial(" + data.getPicture().getMaterial().isDisplaymaterial() + ")");

                mBinding.webviewTclDetail.loadUrl("javascript:setPictureEngineColorcontrol(" + data.getPicture().getEngine().isColorcontrol() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setPictureEngineColorreduction(" + data.getPicture().getEngine().isColorreduction() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setPictureEngineBrightnesscontrol(" + data.getPicture().getEngine().isBrightnesscontrol() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setPictureEngineMixedlight(" + data.getPicture().getEngine().isMixedlight() + ")");

                mBinding.webviewTclDetail.loadUrl("javascript:setPictureImagequalityLocalDimming(" + data.getPicture().getImagequality().isLocalDimming() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setPictureImagequalityHdr(" + data.getPicture().getImagequality().isHdr() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setPictureImagequalityMemc(" + data.getPicture().getImagequality().isMemc() + ")");
                mBinding.webviewTclDetail.loadUrl("javascript:setPictureImagequalityCrystal(" + data.getPicture().getImagequality().isCrystal() + ")");

                mBinding.webviewTclDetail.loadUrl("javascript:setTvSizeContrainbase('" + data.getTvSize().getContrainbase() + "')");
                mBinding.webviewTclDetail.loadUrl("javascript:setTvSizeNotContrainbase('" + data.getTvSize().getNotContrainbase() + "')");
            }
        });

        WebViewManager webViewManager = new WebViewManager(mBinding.webviewTclDetail);
        webViewManager.enableAdaptive();
        webViewManager.enableJavaScript();
        webViewManager.enableJavaScriptOpenWindowsAutomatically();
        webViewManager.enableZoom();
    }
}